/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var tplayerName;
var trow;
var tcol;
var tenemyName;
var tenemyType;
var tenemyShips;
var tenemyStatus;
var xpr;
var gameCounter;
var isMyTurn = false;

gameCounter = 0;
$(document).ready(function() {
    setInterval('updateGameClock()', 1000);
    $('#boards > div').hide();
    $('#boards > div:first-child').show();
    $("#quit").click(function() {
        leaveGame();
    })
    
    $("#players").accordion({
        change:function (event,ui) {
            tenemyName = ui.newContent.attr("id");
            showBoard(tenemyName);
        }
    })
    $("#notificationScroller").slider({
        orientation: "vertical",
        animate: true,
        min: 0,
        max: 520,
        value: 520,
        change: handleSliderChange,
        slide: handleSliderSlide
    });
    callAjax("getgamestatus");
});

function handleSliderChange(e, ui)
{
  var maxScroll = $("#notificationList").attr("scrollWidth") - 
                  $("#notificationList").width();
  $("#notificationList").animate({scrollTop: ui.value * 
     (maxScroll / 100) }, 1000);
}

function handleSliderSlide(e, ui)
{
  var maxScroll = $("#notificationList").attr("scrollWidth") - 
                  $("#notificationList").width();
  $("#notificationList").attr({scrollTop: ui.value * (maxScroll / 100) });
}

function callAjax(call) {
    
    var url = getURL(call);
    var req = generateData(call);
    
    $.ajax({
        data: req,
        url: url,
        timeout: 10000,
        beforeSend: function() {
            showLoading();
        },
        success: function(data) {
            hideLoading();
            processAction(data, call);
            return true;
        },
        error: function(jq, err) {
            hideLoading();
            var msg;
            if (err == "timeout") {
                msg = "Timeout reached while waiting for page";
            } else if (err == "error") {
                msg = "General error while waiting for page";
            } else if (err == "abort") {
                msg = "Page aborted";
            } else {
                msg = "Unknown error, Please try again later";
            }
            showAlert(msg);
            return false;
        }
    });
    return false;
}

function processAction(data, call) {
    if (data.redirect)
        window.location.href = data.redirect;
    var ret = jQuery.parseJSON(data);
    if (ret.r === "ERROR") {
        showAlert(ret.e, call);
    } else if (ret.r === "OK") {
        if (call == "getNextPlayer")
            tplayerName = ret.i;
        switch (ret.n) {
            case "parseNotices":
                break;
            case "humanPlayTurn":
                if (call == "sendtorpedo")
                    showturnAction(ret.e, "human");
                break;
            case "nextPlayer":
                if (call == "sendtorpedo")
                    showturnAction(ret.e, "human");
                break;
            case "eaPlayTurn":
                break;
            case "gameOver":
                askRestart(ret.i);
                break;
            case "newGame":
                window.location.href = "index.jsp";
                break;
            case "parsegamestatus":
                processGameStatus(ret.i);
                setTimeout("callAjax(\"getgamestatus\")", 3000);
                break;
            default:
                break;
        }
    } else {
        showAlert("Invalid return info");
    }
}

function hideLoading() {
    $("#loading").hide();
}

function showLoading() {
    $("#loading").show();
}

function getURL(call) {
    return "WebUiGame";
}

function generateData(call) {
    var ret = new Object();
    ret.actionName = call;
    switch (call) {
        case "getActivePlayers":
            break;
        case "markonenemyboard":
            ret.currPlayer = tplayerName;
            ret.enemyPlayer = tenemyName;
            ret.col = tcol;
            ret.row = trow;
            break;
        case "unmarkonenemyboard":
            ret.currPlayer = tplayerName;
            ret.enemyPlayer = tenemyName;
            ret.col = tcol;
            ret.row = trow;
            break;
        case "sendtorpedo":
            ret.currPlayer = tplayerName;
            ret.enemyPlayer = tenemyName;
            ret.col = tcol;
            ret.row = trow;
            break;
        case  "viewenemyboard":
            ret.currPlayer = tplayerName;
            ret.enemyPlayer = tenemyName;
            break;
        case "quitgame":
            ret.currPlayer = tplayerName;
            break;
        case "eaPlayTurn":
            ret.currPlayer = tplayerName;
            break;
        case "newgame":
            break;
        case "restartgame":
            break;
        case "getplayenotices":
            ret.currPlayer = tplayerName;
            break;
        case "getEnemyType":
            ret.currPlayer = tenemyName;
            break;
        case "getEnemyShips":
            ret.currPlayer = tenemyName;
            break;
        case "getPlayerStatus":
            ret.currPlayer = tenemyName;
            break;
        default:
            break;
    }
    return ret;
}

function setBoard(data, owner, status) {
    var i,j;
    if (data != null) {
        for (j = 0; j < data.length; j++) {
            for (i = 0; i < data[j].length; i++) {
                $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').removeClass();
                $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("square");
                if (tenemyName == tplayerName)
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("ownSquare");
                    
                if (data[j][i].sign == "-") {
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("emptySquare");
                } else if (data[j][i].sign == "X") {
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("hitSquare");
                } else if (data[j][i].sign == "@") {
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("markedSquare");
                } else if (data[j][i].sign == "O") {
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("missedSquare");
                } else if (data[j][i].sign == "#") {
                    $('div[data-owner="' + owner + '"] > div[data-col="' + i + '"][data-row="' + j + '"]').addClass("subSquare");
                } else {
                    showAlert("Invalid input from server in row " + j + " and col " + i + " sign is:" +data[j][i].sign + "" );
                    return;
                }
            }
        }
    }
    $("[data-col][data-row]").unbind("click");
    $(".markedSquare").click(function() {
        tcol = $(this).attr("data-col");
        trow = $(this).attr("data-row");
        
        openUnmarkDialog();
    })
    $(".emptySquare").click(function() {
        tcol = $(this).attr("data-col");
        trow = $(this).attr("data-row");
        
        openMarkDialog();
    })
    $(".ownSquare").unbind("click");
}

function setPlayer(name, status, type, subs) {
    displayStatus(name, type, status, subs);
    $("div[data-playerinfo='" + name + "'").css('filter', 'alpha(opacity=60)');
}

function myTurn() {
    return isMyTurn;
}

function openUnmarkDialog() {
    $("#action").dialog("destroy");
    $("#action").html("Please select oyur next move");
    if (myTurn()) {
        $("#action").dialog({
            resizeable: false,
            modal: true,
            width: 400,
            draggable: false,
            resizable: false,
            autoopen: true,
            buttons: {
                "Unmark": function() {
                    $(this).dialog("close");
                    callAjax("unmarkonenemyboard");
                },
                "Attack": function() {
                    $(this).dialog("close");
                    callAjax("sendtorpedo") ;
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    } else {
        $("#action").dialog({
            resizeable: false,
            modal: true,
            width: 400,
            draggable: false,
            resizable: false,
            autoopen: true,
            buttons: {
                "Unmark": function() {
                    $(this).dialog("close");
                    callAjax("unmarkonenemyboard");
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    }
}

function openMarkDialog() {
    $("#action").dialog("destroy");
    $("#action").html("Please select your next move");
    if (myTurn()) {
        $("#action").dialog({
            resizable: false,
            width: 400,
            modal: true,
            dragabble: false,
            resizeable: false,
            autoopen: true,
            buttons: {
                "Mark": function() {
                    $(this).dialog("close");
                    callAjax("markonenemyboard");
                },
                "Attack": function() {
                    $(this).dialog("close");
                    callAjax("sendtorpedo") ;
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    } else {
        $("#action").dialog({
            resizable: false,
            width: 400,
            modal: true,
            dragabble: false,
            resizeable: false,
            autoopen: true,
            buttons: {
                "Mark": function() {
                    $(this).dialog("close");
                    callAjax("markonenemyboard");
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    }
}

function leaveGame() {
    $("#action").html("Are you sure you want to quit?");
    $("#action").dialog({
        resizable: false,
        width: 400,
        modal: true,
        dragabble: false,
        resizeable: false,
        autoopen: true,
        buttons: {
            "Yes": function() {
                $(this).dialog("close");
                callAjax("quitgame") ;
            },
            "No": function() {
                $(this).dialog("close");
            }
        }
    })
}

function showAlert(msg, call) {
    $("#errorMsg").html(msg);
    $("#errorMsg").dialog({
        modal: true,
        draggable:false,
        resizeable: false,
        stack: false,
        buttons: {
            Ok: function () {
                $(this).dialog("close");
                if (call == "getgamestatus")
                    callAjax(call);
            }
        }
    });
}

function showturnAction(msg, type) {
    $("#computerAction").html(msg);
    $("#computerAction").dialog({
        modal: true,
        draggable:false,
        resizeable: false,
        stack: false,
        buttons: {
            "next": function () {
                $(this).dialog("close");
            }
        }
    });
}

function displayStatus(name, type, status, subs) {
    $("div[data-playerinfo='" + name + "'] > p").html();
    var msg = "<h4>Player Status:" + status + "</h4>";
    msg += "<h4>Player Type:" ;
    if (name == "self")
        msg += "You</h4>"
    else
        msg += "" + type + "</h4>";
    msg += "<h4>Remaining ships:</h4>";
    msg += "<ul>";
    var i,j;
    for (i = 0; i < subs.length; i++) {
        for (j = 0; j < subs[i].length; j++) {
            if (subs[i][j] != "")
                msg += "<li>" + subs[i][j] + "</li>";
        }
    }
    msg += "</ul>";
    $("div[data-playerinfo='" + name + "'] > p").html(msg);
    $("#players").accordion( "resize" );
}

function askRestart(winner) {
    $("#computerAction").attr("title", "Game Ended");
    $("#computerAction").html(winner + "is the winner<br />Would you like to start new game or restart with the current settings?");
    $("#computerAction").dialog({
        modal: true,
        draggable:false,
        resizeable: false,
        stack: false,
        buttons: {
            "New Game": function () {
                $(this).dialog("close");
                callAjax("newgame");
            },
            "Restart": function() {
                $(this).dialog("close");
                callAjax("restartgame");
            }
        }
    });
}

function sleep(naptime) {
       
    naptime = naptime * 1000;
    var sleeping = true;
    var now = new Date();
    var alarm;
    var startingMSeconds = now.getTime();
    while(sleeping){
        alarm = new Date();
        alarmMSeconds = alarm.getTime();
        if(alarmMSeconds - startingMSeconds > naptime){
            sleeping = false;
        }
    }        
}

function updateGameClock() {
    gameCounter++;
    
    var gameSeconds = gameCounter%60;
    var gameMinutes = Math.floor(gameCounter/60);
    var gameHours = Math.floor(gameMinutes/60);
    gameMinutes = gameMinutes%60;
    gameHours = gameHours%24;
    
    gameCounter = gameCounter%(24*60*60);
    var string;
    var stringSeconds;
    if (gameSeconds < 10)
        stringSeconds = "0" + gameSeconds;
    else
        stringSeconds = gameSeconds;
    var stringMinutes;
    if (gameMinutes < 10)
        stringMinutes = "0" + gameMinutes;
    else
        stringMinutes = gameMinutes;
    
    string = "Game time: " + gameHours + ":" + stringMinutes + ":" + stringSeconds;
    $("#gameClock").html(string);
}

function showBoard(name) {
    $('#boards > div').hide();
    $('div[data-owner="' + name + '"]').show();
}

function processGameStatus(data) {
    
    var boards = data.boards;
    var players = data.players;
    var subs = data.submarines;
    var i;
    
    str = "Now Playing: " + players[0][0] + "";
    $("#thisTurn").html(str);
    
    if (players[0][0] == tplayerName)
        isMyTurn = true;
    else
        isMyTurn = false;
    
    for (i = 0; i < boards.length; i++) {
        var name = players[i][0];
        var type = players[i][1];
        var status = players[i][2];
        
        setBoard(boards[i], name, status);
        setPlayer(name, status, type, subs[i]);
    }
}